package com.hitalkie.teacher.util;

import com.hitalkie.teacher.app.TalkieApplication;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Date 6/14/16
 *
 * @author charliema
 */
public class OkHttpManager {

    public static OkHttpClient client;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    static {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);

            client = builder
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .addInterceptor(
                            new Interceptor() {
                                @Override
                                public Response intercept(Interceptor.Chain chain) throws IOException {
                                    Request original = chain.request();
                                    Request.Builder requestBuilder = original.newBuilder();
                                    requestBuilder.header("Content-Type", "application/json");
                                    if (TalkieApplication.isSignIn()) {
                                        requestBuilder.header("X-Talkie-Token", TalkieApplication.getToken());
                                    }
                                    requestBuilder.header("X-Talkie-Language", TalkieApplication.getLanguage());
                                    requestBuilder.header("X-Talkie-Role", "teacher");
//                                            requestBuilder.header("X-Talkie-Role", "student")
                                    requestBuilder.header("X-Talkie-Platform", "Android");
//                                    requestBuilder.header("X-Talkie-Api", "v2");
                                    requestBuilder.header("X-Talkie-Version", Utils.getAppVersionName(TalkieApplication.sInstance));
//                                            .method(original.method(), original.body())
                                    return chain.proceed(requestBuilder.build());
                                }
                            })
                    .addInterceptor(logging)
                    .build();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
